package com.tyf.bookreader.manager;

import cn.hutool.core.bean.BeanUtil;
import com.tyf.bookreader.constant.RedisConstants;
import com.tyf.bookreader.domain.BrChapter;
import com.tyf.bookreader.dto.ChapterDto;
import com.tyf.bookreader.exception.BrException;
import com.tyf.bookreader.mapper.BrChapterMapper;
import com.tyf.bookreader.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description TODO
 * @Author shallow
 * @Date 2023/4/2 15:05
 */
@Component
@Slf4j
public class ChapterCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BrChapterMapper chapterMapper;

    public ChapterDto getChapterById(Long chapterId){
        Object chapterDto = redisService.hGet(RedisConstants.CHAPTER_INFO_CACHE_KEY, String.valueOf(chapterId));
        if(!Objects.isNull(chapterDto)){
            log.debug("走缓存");
            return BeanUtil.toBean(chapterDto,ChapterDto.class);
        }
        log.debug("走数据库");
        BrChapter chapter = chapterMapper.selectById(chapterId);
        if (Objects.isNull(chapter)){
            throw new BrException("没有本章节");
        }
        ChapterDto chapterDto1 = ChapterDto.builder()
                .id(chapter.getId())
                .bookId(chapter.getBookId())
                .chapterNum(chapter.getChapterNum())
                .chapterName(chapter.getChapterName())
                .chapterUpdateTime(chapter.getUpdateTime()).build();
        redisService.hSet(RedisConstants.CHAPTER_INFO_CACHE_KEY,String.valueOf(chapterId),chapterDto1,RedisConstants.COMMON_CACHE_TIME);
        return chapterDto1;
    }
}
